using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CreateEnemy : MonoBehaviour
{
    [Header("每隔多少时间检查一次")]
    public float CheckTime = 15.0f;

    [Header("对象池的大小")]
    public int poolSize;

    public float CreateRangeX = 4.0f;

    public Transform Player;
    public float DisToPlayer = 7.0f;
    public GameObject Enemy;
    public int DroneNum = 0; //无人机数量
    private float m_timer = 0;

    private List<GameObject> objectPool = new List<GameObject>();


    
    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < poolSize; i++)
        {
            GameObject enemy = Instantiate(Enemy, Vector3.zero, Quaternion.identity);
            enemy.SetActive(false);
            objectPool.Add(enemy);
        }
    }

    // Update is called once per frame
    void Update()
    {
        Follow();
        //每隔10秒检查一次
        m_timer += Time.deltaTime;
        if (m_timer >= CheckTime) {
            Check();
            m_timer = 0;
        }
    }

    void Follow() {
        //始终位于地图的上方某处
        transform.position = new Vector2(transform.position.x, Player.position.y + 6.0f);
    }

    void Check() {
        //检查场上无人机数量
        if (DroneNum < 3) {
            Create();
        }
    } //销毁在Enemy自己的脚本里

    void Create() {
        GameObject enemy = GetPooledObject();
        if (enemy != null)
        {
            float x = Random.Range(transform.position.x, transform.position.x + CreateRangeX);
            enemy.transform.position = new Vector2(x, transform.position.y);
            enemy.SetActive(true);
        }
    }

    GameObject GetPooledObject()
    {
        for (int i = 0; i < objectPool.Count; i++)
        {
            if (!objectPool[i].activeInHierarchy)
            {
                return objectPool[i];
            }
        }
        return null;
    }
}
